/**
 * Created by Dell on 2017.10.11.
 */
var con_select ;
var reg_select ;
var chr_select ;
var chrsy_select ;
var DWType_select;
var con_type = 1;
var reg_val = '000' ;
var chr_val = '071';
var chrsy_val = '1';
var drawnItems;
var iconSize = [16,16];
var reportData =[
    {"field":"CODE","name":"流水号","unit":""},
    {"field":"LandZdID","name":"宗地ID","unit":""},
    {"field":"LandUser","name":"使用权利人","unit":""},
    {"field":"Address","name":"权利人坐落","unit":""},
    {"field":"AreaOfLand","name":"土地面积","unit":"(m³)"},
    {"field":"LandCertificateID","name":"土地权证号","unit":""},
    {"field":"LandType_Name","name":"用地性质","unit":""},
    {"field":"LandCertificateDate","name":"发证年份（土地）","unit":""},
    {"field":"AreaOfStructure","name":"房屋建筑面积","unit":"(m³)"},
    {"field":"CertificateID","name":"房屋权证号","unit":""},
    {"field":"CertificateDate","name":"发证年份（房屋）","unit":""},
    {"field":"DWType_Name","name":"单位性质","unit":""},
    {"field":"ZGDW_Name","name":"主管单位","unit":""},
    {"field":"BookValue","name":"房屋账面价值","unit":"(元)"},
];
var Token = '123'
$(function(){

    // 加入载入图标
    var spinloading =new Spinner({radius: 10, length: 0, width: 8, lines:7,color:"#436c8f", trail: 40,className: 'myspinner'})
        .spin(document.getElementsByClassName('spinLoading')[0]);

    // javax发起请求时，显示载入图标
    $(document).ajaxStart(function(){
        $(".loadingDiv").show();
    });

    // javax请求结束时，隐藏图标
    $(document).ajaxStop(function(){
        $(".loadingDiv").hide();
    });

    // 一级选择
    con_select = $('#con_select').customSelect({
        width:158,
        lineHeight:28
    });
    // 使用单位
    chrsy_select = $('#chrsy_select').customSelect({
        width:180,
        lineHeight:28,
        show:false
    });
    // 单位性质
    DWType_select = $('#DWType_select').customSelect({
        width:180,
        lineHeight:28,
        show:false
    });

    var reportBoxHeight = $('.contrastMain').height()-$('.reporttop').height()- $('.checkLists').height()-40-40-20;
    var reportBoxWidth = $('.contrastMain').width() - 20*2;
    $('.reportContent').height(reportBoxHeight);
    $('.reportContent').width(reportBoxWidth);

    //乡镇
    $.post(config.serviceUrl+ "/api/Region", {
            "DATA": {
                "ID": "000",
                "Token" : Token,
            }
        },
        function (jsonData) {
            if(jsonData !=null){
                var reg = jsonData.Region;
                var regsult = '';
                for(var i=0; i<reg.length;i++){
                    regsult +='<option value="'+ reg[i].Region_ID+'">'+ reg[i].Region_Name +'</option>'
                }
                reg_select = $('#reg_select').append(regsult).customSelect({
                    width:158,
                    lineHeight:28,
                });
                reg_select.change(function(){
                    reg_val = reg_select.getValue();
                });
            }
        }
    );

    // 主管单位
    $.post(config.serviceUrl+ "/api/Chr", {
            "DATA": {
                "Prefix": "071",
                "Token" : Token,
            }
        },
        function (jsonData) {
            //console.log(jsonData)
            if(jsonData !=null){
                var chr = jsonData.CHR;
                var chrsult = '';
                for(var i=0; i<chr.length;i++){
                    chrsult +='<option value="'+ chr[i].CHR_ID+'">'+ chr[i].CHR_Name +'</option>'
                }
                chr_select = $('#chr_select').append(chrsult).customSelect({
                    width:280,
                    lineHeight:28,
                    show:false
                });
            }
        }
    );

    con_select.change(function(){
        con_type = con_select.getValue();
        if(con_type == 1){
            reg_select.show();
            chr_select.hide();
            chrsy_select.hide();
            DWType_select.hide();
        }
        else if(con_type == 2){
            chr_select.show();
            reg_select.hide();
            DWType_select.hide();
            //(chr_select.getValue() != '071') ? chrsy_select.show() : chrsy_select.hide();
            chr_select.change(function(){
                chr_val = chr_select.getValue();
                if(chr_val != '071'){
                    chrsy_select.show();
                    $.post(config.serviceUrl+ "/api/Chr", {
                            "DATA": {
                                "Prefix": chr_val,
                                "Token" : Token,
                                "async":true
                            }
                        },
                        function (jsonData) {
                            //console.log(jsonData)
                            if(jsonData !=null){
                                if(jsonData.CHR[0].subCHR){
                                    var chrsy = jsonData.CHR[0].subCHR;
                                    var chrsysult = ' <option value="'+chr_val+'">全部使用单位</option>';
                                    for(var i=0; i<chrsy.length;i++){
                                        chrsysult +='<option value="'+ chrsy[i].CHR_ID+'">'+ chrsy[i].CHR_Name +'</option>'
                                    }
                                    $('#chrsy_select').prev('.select_box').remove();
                                    chrsy_select = $('#chrsy_select').html(chrsysult).customSelect({
                                        width:180,
                                        lineHeight:28,
                                    });
                                    chrsy_select.change(function(){
                                        chrsy_val = chrsy_select.getValue();
                                    })
                                }
                            }
                        }
                    );
                }else {
                    chrsy_select.hide();
                }
            });

        }
        else{
            chr_select.hide();
            chrsy_select.hide();
            reg_select.hide();
            DWType_select.show();
        }
    });

    $.each(reportData,function(index,data){
        var checked = "";
        if(index<3){
            checked = "checked";
        }
        $('.checkLists').append('<li><input type="checkbox" value="'+data.field+'" '+checked+' class="reType" unit="'+data.unit+'">'+data.name+'</li>')
    });

    $('.reType').click(function(){

    });

    $('.getReport').click(function(){
        //console.log(reg_select.getValue())
        var val = getVal().str;
        if(con_type == 1){
            Region_ID = reg_val;
            CHR_ID = '';
            DWType_ID = '';
        }else if(con_type == 2){
            Region_ID = '';
            CHR_ID = chr_val;
            if(chr_val != '071'){
                CHR_ID = chrsy_select.getValue();
            }
            DWType_ID = '';
        }else{
            Region_ID = '';
            CHR_ID = '';
            DWType_ID = DWType_select.getValue();
        }
        test_List(Region_ID,CHR_ID,DWType_ID,val)
    });
    $('.getReport').trigger('click');

    $('.exportReport').click(function(){
        var $obj = $('.reportContent');
        exportExcel($obj);
    })

});

//报表请求
function test_List(Region_ID,CHR_ID,DWType_ID,outFields) {
    var url = config.serviceUrl + "/api/Fa";
    $.post(url, {
            "DATA": {
                "Action": "List",     //
                "Region_ID": Region_ID,     //可省略
                "CHR_ID": CHR_ID,      //可省略
                "DWType_ID": DWType_ID,      //可省略
                //"outFields": "Purpose,UseLife,UsedMonth,AreaOfFloor,BuildingStructure,PropertyStatus,",
                "outFields": outFields,
                "Token": Token
            }
        },
        function (jsondata) {

            if(outFields.length == 0){
                $('#reportTable thead tr').html('');
                $('#reportTable tbody').html('<tr><td>暂无数据</td></tr>');
            }
            //console.log(JSON.stringify(result));
            if(jsondata.Success == true){
                if(jsondata.FA){


                    var strh= '';
                    var theadList = getVal().theadList;
                    var unitList = getVal().unit;
                    strh += '<th>序号</th>';
                    for(var i=0;i<theadList.length;i++){
                        strh += '<th>'+theadList[i]+unitList[i]+'</th>'
                    }
                    $('#reportTable thead tr').html(strh);


                    var fas = jsondata.FA;
                    var len = outFields.split(",");
                    //for(var i=0;i<fa.length;i++){}
                    var strb = '';
                    $.each(fas,function(index,fa){
                        strb +='<tr>';
                        strb +='<th>'+ (index+1)+'</th>';
                        for(var i = 0;i<len.length;i++){
                            strb +='<td>'+filValue(fa[len[i]])+'</td>';
                        }
                        strb +='</tr>'
                    });
                    $('#reportTable tbody').html(strb);

                    //console.log(jsondata)
                    //console.log(fa[0])
                }else {
                    $('#reportTable thead tr').html('');
                    $('#reportTable tbody').html('<tr><td>暂无数据</td></tr>');
                }

            }
        });
}

// 导出报表
function exportExcel(obj) {
    var objHtml = obj.html();
    var nodata = obj.find('td');
    var excelName = RthyinfoFormat.formatTMNoYear(new Date());
    if (objHtml == "" || nodata.length == 1) {
        $.toast({
            text: '报表内容不能为空，生成报表内容后再导出！',
            icon: 'info',
            position: "mid-center",
            stack: false,
            allowToastClose: false,
            loader: false,
            bgColor: "#3bb9d4",
            textColor: "#fff",
            timeout: 3000,
        });
    } else {
        $.when().done(function(){
            var file;
            try {
                file = new Blob(["\ufeff" + objHtml], { type: "application/x-xls;charset=utf-8" });
                saveAs(file, excelName+".xls");
            }
            catch (e) {
                saveTextAs("\ufeff" + objHtml, excelName + ".xls");
            }
            $.toast({
                text: '报表内容成功导出!',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "#3bb9d4",
                textColor: "#fff"
            });

        })
    }
}

// 得到复选框类型
var getVal = function(){
    var data = {};
    var theadList = [];
    var str = '';
    var unitList = [];
    $('.reType').each(function(){
        if($(this).is(":checked")){
            if(str=="") str = $(this).val();
            else  str += "," + $(this).val();
            //console.log($(this))
            unitList.push($(this).attr('unit'));
            theadList.push($(this).parent().text());
        }
    });
    data.str = str;
    data.theadList = theadList;
    data.unit = unitList;
    return data;
};

var filValue = function(x){
    if(x==="" || typeof(x) == "undefined" || x==null || x == "undefined"){
        return "";
    }else {
        return x;
    }
};